import userUtils from "./user-utils";
export default {
	loginByWeChat(userInfo, paltform = "wechat", successFn) {
		showLoading()
		// 参考：https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=微信登录
		// 官方api提供：微信小程序登录和微信账号登录
		let userLoginRes = null //缓存登录信息
		let provider = paltform === "wechat" ? 'weixin' : ''
		uni.login({
			provider: provider
		}).then((res) => {
			// 先登录账号
			console.log("login", res)
			res = res.filter(item => {
				return item != null
			})[0]
			console.log("login1", res)
			let code = res.code
			let action = paltform == "wechat" ? 'loginByWeixin' : 'loginByAlipay'
			return uniCloud.callFunction({
				name: 'user-center',
				data: {
					action: action,
					params: {
						code
					}
				}
			})
		}).then(res => {
			// 查询小程序用户表是否存在用户
			userLoginRes = res
			console.log("loginByWeixin", res, userLoginRes)
			if (res.result.code != 0)
				throw res.result.msg
			let openId = res.result.openid
			return uniCloud.callFunction({
				name: 'database',
				data: {
					collection: 'mpuser',
					type: 'doc',
					docId: openId
				}
			})
		}).then(res => {
			console.log("query-mpuser-data", res)
			if (res.result.data.length > 0) {
				return new Promise((resolve, reject) => {
					resolve("用户已经存在")
				})
			} else {
				// 添加到小程序用户表
				userInfo._id = userLoginRes.result.openid
				return uniCloud.callFunction({
					name: 'database',
					data: {
						collection: 'mpuser',
						type: 'add',
						add: userInfo
					}
				})
			}
		}).then((res) => {
			console.log("add-mpuser-data", res)
			this.loginSuccess(userLoginRes, successFn)
		}).catch(err => {
			console.error(err)
			let errMsg = err || "小程序登录失败"
			toast(errMsg)
		}).finally(() => {
			hideLoading()
		})
	},
	sendEmailCode(email, type = "login") {
		showLoading()
		uniCloud.callFunction({
			name: 'api-request',
			data: {
				action: 'sendEmailCode',
				mail: email,
				type: type
			}
		}).then(result => {
			toast("验证码发送成功！")
		}).catch((e) => {
			console.error(e)
			toast("验证码发送失败！")
		}).finally(() => {
			hideLoading()
		})
	},
	sendMobildCode(mobile, type = "login") {
		showLoading()
		uniCloud.callFunction({
			name: 'api-request',
			data: {
				action: "sendMobileCode",
				mobile: mobile,
				type: type
			}
		}).then(result => {
			toast("验证码发送成功！")
		}).catch((e) => {
			toast("验证码发送失败！")
		}).finally(() => {
			hideLoading()
		})
	},
	loginByEmail(email, password, code, successFn) {
		showLoading()
		let reqPara = {}
		let params = {}
		if (password != "") {
			reqPara.action = "login"
			params.username = email
			params.password = password
		}
		if (code != "" && code.length == 6) {
			reqPara.action = "loginByEmail"
			params.email = email
			params.code = code
		}
		reqPara.params = params
		uniCloud.callFunction({
			name: 'user-center',
			data: reqPara
		}).then(res => {
			console.log("loginByEmail",res)
			this.loginSuccess(res, successFn)
		}).catch(err => {
			console.error(e)
			toast("登录失败，请稍后再试！")
		}).finally(() => {
			hideLoading()
		})
	},
	bindYzmData(type = 1, key, code, successFn) { //type：1邮箱，2手机号
		showLoading()
		let token = uni.getStorageSync("token");
		let uid = uni.getStorageSync("uid");
		let reqPara = {}
		let params = {
			uid: uid,
			code: code,
			email: key,
			mobile: key
		}
		reqPara.uniIdToken = token
		reqPara.action = type == 1 ? "bindEmail" : "bindMobile"
		reqPara.params = params
		uniCloud.callFunction({
			name: 'user-center',
			data: reqPara
		}).then(res => {
			let result = res.result
			if (result.code != 0) {
				toast(result.msg)
				return
			}
			toast("绑定成功！")
			console.log("bindYzmData", res)
			userUtils.getUserInfo(successFn)
		}).catch(err => {
			console.error(e)
			toast("绑定失败，请稍后再试！")
		}).finally(() => {
			hideLoading()
		})
	},
	loginByMobile(mobile, password, smsCode, successFn) {
		showLoading()
		let reqPara = {}
		let params = {}
		if (password != "") {
			reqPara.action = "login"
			params.username = mobile
			params.password = password
		}
		if (smsCode != "" && smsCode.length == 6) {
			reqPara.action = "loginBySms"
			params.mobile = mobile
			params.code = smsCode
		}
		reqPara.params = params
		uniCloud.callFunction({
			name: 'user-center',
			data: reqPara
		}).then(res => {
			this.loginSuccess(res, successFn)
		}).catch(err => {
			toast("登录失败，请稍后再试！")
		}).finally(() => {
			hideLoading()
		})
	},
	loginSuccess(res, successFn) {
		console.log("loginSuccess", res)
		if (res.result.code === 0) {
			toast("登陆成功！")
			uni.setStorageSync('token', res.result.token)
			uni.setStorageSync('uid', res.result.uid)
			userUtils.getUserInfo(successFn)
		} else {
			let msg = res.result.msg
			toast(msg)
		}
	}
}

function toast(content) {
	uni.showToast({
		title: content,
		icon: 'none'
	})
}

function showLoading() {
	uni.showLoading({
		title: "提交中...",
		mask: true
	})
}

function hideLoading() {
	uni.hideLoading()
}
